package com.alex.blog.config;

import com.alex.blog.pojo.User;
import com.alex.blog.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

// 登录 -> 认证 -> 授权
public class MyRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行授权 ...");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        Subject subject = SecurityUtils.getSubject();
        User principals = (User) subject.getPrincipal();

//        info.addStringPermission("user:add");
        System.out.println("当前用户拥有权限: " + principals.getPerms());
        if (principals.getPerms() != null) {
            info.addStringPermission(principals.getPerms());
        }

        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行认证 ...");

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        User user = userService.getOneByUserName(token.getUsername());

        if (user == null) {
            return null;
        }

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), "");
        return info;
    }
}
